<template>
	<mescroll-uni
		:bottombar="false"
		:down="downOption"
		:up="upOption"
		@init="mescrollInit"
		@down="downCallback"
		@up="upCallback"
		height="100%"
	>
		<view class="swiper_box">
			<view class="notice">
				<u-notice-bar :text="scorllList[0].content" mode=""></u-notice-bar>
			</view>
			<u-swiper
				:list="list"
				indicator
				indicatorMode="line"
				circular
				height="520rpx"
				radius="0"
				indicatorStyle="margin-bottom:30rpx;"
				keyName="url"
				@click="goWebview"
			></u-swiper>
		</view>

		<view class="home_content">
			<view class="cardList">
				<image
					:src="imgUrl + 'imgs/home/card1.png'"
					alt=""
					class="card1"
					@click="goUrl('/subPages/home/memoryHall/index')"
				></image>
				<image
					:src="imgUrl + 'imgs/home/card2.png'"
					alt=""
					class="card1"
					@click="goUrl('/subPages/home/ancestralTemple/index')"
				></image>
				<image
					:src="imgUrl + 'imgs/home/card3.png'"
					alt=""
					class="card2"
					@click="goUrl('/subPages/home/clan/index')"
				></image>
			</view>

			<!-- 纪念活动公告 -->
			<image
				class="activity_title"
				:src="imgUrl + 'imgs/home/activity_title.png'"
				@click="openGetUserInfo = true"
			></image>

			<view
				class="messageBox"
				v-for="(item, index) in messageList"
				:key="index"
				@click="goUrl('/subPages/chaoshan/detail?item=' + JSON.stringify(item))"
			>
				<!-- <image
					class="messageBox_decorate"
					:src="imgUrl + 'imgs/home/decoration.png'"
					mode=""
				></image> -->
				<view class="userInfo">
					<image
						:src="imgUrl + 'imgs/home/activity_avater.png'"
						alt=""
						class="avater"
					></image>
					<view>
						<view class="name">先贤祠墓念堂</view>
						<view class="date">{{ item.createdAt }}</view>
					</view>
				</view>
				<view class="message_title" v-if="item.articleTitle">{{ item.articleTitle }}</view>
				<view class="intro">{{ item.articleContent }}</view>
				<view
					class="imageList"
					v-if="item.articleUrlType == 1"
					:style="{
						gridTemplateColumns:
							item.articleUrls.length === 4 ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)'
					}"
				>
					<image
						:src="ele"
						alt=""
						v-for="(ele, i) in item.articleUrls"
						:key="i"
						:style="{
							width: item.articleUrls.length === 4 ? '310rpx' : '204rpx',
							height: item.articleUrls.length === 4 ? '310rpx' : '204rpx'
						}"
						@click.native.stop="previewImg(item.articleUrls, i)"
						mode="aspectFill"
					></image>
				</view>
				<view class="videoClass" v-if="item.articleUrlType == 2">
					<image
						v-if="item.longAis === 'width'"
						:src="item.videoCover"
						alt=""
						mode="cover"
						style="width: 638rpx; height: 360rpx"
					></image>
					<image
						v-else
						:src="item.videoCover"
						alt=""
						mode="cover"
						style="width: 270rpx; height: 360rpx"
					></image>
					<image
						class="stop"
						:src="imgUrl + 'imgs/chaoshan/stop.png'"
						@click="playVideo"
					></image>
				</view>
				<view class="footer">
					<image
						:src="imgUrl + 'imgs/home/more.png'"
						alt=""
						class="more"
						@click.stop="showMore(item)"
					></image>
					<view class="display_flex" @click.stop="setLike(item, index)">
						<up-icon
							name="thumb-up"
							size="48rpx"
							v-if="item.praise == 0 || item.praise == 2"
						></up-icon>
						<up-icon name="thumb-up-fill" color="#FF4C5A" size="48rpx" v-else></up-icon>
						<view>{{ item.praiseNum }}</view>
					</view>
				</view>
			</view>
		</view>
	</mescroll-uni>

	<!-- 按钮弹框 -->
	<u-popup
		:show="showMoreFunc"
		bgColor="rgba(0,0,0,0)"
		@close="closeMore"
		custom-style="padding:0 16rpx 0;"
	>
		<view class="button_list">
			<u-button
				open-type="share"
				@click="shareWx"
				shape="circle"
				:custom-style="{ ...moreBtnStyle, marginBottom: 0, borderRadius: 0 }"
			>
				分享
			</u-button>
			<u-button
				shape="circle"
				:custom-style="{ ...moreBtnStyle, marginBottom: 0, borderRadius: 0 }"
				@click="report"
			>
				举报
			</u-button>
		</view>
		<u-button
			shape="circle"
			:custom-style="{ ...moreBtnStyle, fontWeight: 600 }"
			@click="closeMore"
		>
			取消
		</u-button>
	</u-popup>

	<!-- 获取用户信息弹框 -->
	<!-- #ifdef MP -->
	<editUserModal v-model:show="openGetUserInfo" @closeEdit="" @editSuccess=""></editUserModal>
	<!-- #endif -->
</template>

<script setup>
import { onMounted, ref } from 'vue';
import {
	onPageScroll,
	onReachBottom,
	onShow,
	onHide,
	onReady,
	onLoad,
	onShareAppMessage
} from '@dcloudio/uni-app';
import { imgUrl } from '@/external/utils/imgUrl.js';
import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js';
import { previewImg } from '@/utils/previewImg.js';
import HomeApi from '@/API/home/index.js';
import _ from 'lodash';
import { timeFormat } from '@/node_modules/uview-plus';
// #ifdef MP
import editUserModal from '@/components/xghc-editUserModal/index.vue';
// #endif

// 调用mescroll的hook (注: mescroll-uni不用传onPageScroll,onReachBottom, 而mescroll-body必传)
const { getMescroll, mescrollInit } = useMescroll(); // 调用mescroll的hook
const navHeight = getApp().globalData.navHeight;
const homeApi = new HomeApi();
const search = ref('');
const dynamicLatestId = ref(0); //最后一条动态id
const messageList = ref([]); //信息列表

//翻页信息
const downOption = ref({
	auto: false
});
const upOption = ref({
	// auto: false
});

const openGetUserInfo = ref(false);

//轮播图
const list = ref([{}]);
const scorllList = ref([
	{
		content: ''
	}
]);

// 更多按钮
const showMoreFunc = ref(false);
const moreBtnStyle = {
	height: '120rpx',
	borderRadius: '26rpx 26rpx 26rpx 26rpx',
	backgroundColor: '#fff',
	fontWeight: '400',
	fontSize: '40rpx',
	color: '#007AFF',
	marginBottom: '16rpx'
};
let reportedId = ref('');
let isSelf = ref('');
//初始化
onMounted(() => {
	// if (!uni.getStorageSync('ACCESS_TOKEN')) {
	// 	uni.reLaunch({
	// 		url: '/pages/login/login'
	// 	});
	// }

	// const query = uni.createSelectorQuery().in(this);
});
onLoad(() => {
	downCallback();
});
onShow(() => {
	query();
});

const goWebview = (e) => {
	if (list[e].link) {
		goUrl(`/subPages/others/webview?src=${list[e].link}`);
	}
};

//分享微信
onShareAppMessage(() => {
	const promise = new Promise((resolve) => {
		setTimeout(() => {
			resolve({
				title: '公告转发'
			});
		}, 2000);
	});
	return {
		title: '公告转发',
		path: '/page/user?id=123',
		promise
	};
});

const getImageInfo = async (url) => {
	let res = await wx.getImageInfo({
		src: url
	});
	if (res.width > res.height) {
		return true;
	} else {
		return false;
	}
};

const query = () => {
	homeApi
		.getBannerList()
		.then((res) => {
			list.value = res.data.items;
		})
		.catch((e) => {});
	homeApi
		.getScorllList()
		.then((res) => {
			scorllList.value = res.data.items;
		})
		.catch((e) => {});
};
/* 自定义下拉刷新的回调,不使用useMescroll的downCallback */
const downCallback = (mescroll) => {
	dynamicLatestId.value = 0;
	getMescroll().resetUpScroll();
};

/*上拉加载的回调: 其中mescroll.num:当前页 从1开始, mescroll.size:每页数据条数,默认10 */
const upCallback = (mescroll) => {
	homeApi
		.getNoticeList({
			pageIndex: mescroll.num,
			reqNum: mescroll.size
			// ,articleType: 1
		})
		.then((res) => {
			console.log(res.data.items);
			const curPageData = res.data.items || []; // 当前页数据
			if (mescroll.num == 1) messageList.value = [];
			for (let i = 0; i < curPageData.length; i++) {
				curPageData[i].articleUrls = curPageData[i].articleUrls.split(',');
				if (curPageData[i].articleUrlType === 2) {
					curPageData[i].longAis = 'width';
					//视频计算宽高
					uni.getImageInfo({
						src: curPageData[i].videoCover,
						success: function (r) {
							console.log(r);
							if (r.width > r.height) {
								curPageData[i].longAis = 'width';
							} else {
								curPageData[i].longAis = 'height';
							}
						}
					});
				}
			}
			messageList.value = messageList.value.concat(curPageData);
			console.log('messageList.value', messageList.value);
			mescroll.endSuccess(curPageData.length); // 请求成功, 结束加载
		})
		.catch(() => {
			mescroll.endErr(); // 请求失败, 结束加载
		});
};
const setLike = _.throttle(function (item) {
	if (item.praise == 1) {
		item.praise = 0;
		homeApi
			.praiseNotice({
				id: item.id,
				praise: '0'
			})
			.then((res) => {
				item.praiseNum--;
			})
			.catch(() => {});
	} else {
		item.praise = 1;
		homeApi
			.praiseNotice({
				id: item.id,
				praise: '1'
			})
			.then((res) => {
				item.praiseNum++;
			})
			.catch(() => {});
	}
}, 1000);
// const setLike = _.throttle(function(item) {
// 	if (item.praise == 1) {
// 		item.praise = 0;
// 		homeApi
// 			.deleteLikeApi({
// 				dynamicId: item.dynamicId,
// 				likeType: '1',
// 				commentId: 0,
// 				commentCommentId: 0
// 			})
// 			.then((res) => {
// 				item.praiseNum--;
// 			})
// 			.catch(() => {});
// 	} else {
// 		item.praise = 1;
// 		homeApi
// 			.likeApi({
// 				dynamicId: item.dynamicId,
// 				likeType: '1',
// 				commentId: 0,
// 				commentCommentId: 0
// 			})
// 			.then((res) => {
// 				item.praiseNum++;
// 			})
// 			.catch(() => {});
// 	}
// }, 1000);

const del = () => {
	homeApi
		.deleteDynamicApi({
			dynamicId: reportedId.value
		})
		.then((res) => {
			uni.showToast({
				title: '删除成功'
			});
			showMoreFunc.value = false;
			dynamicLatestId.value = 0;
			getMescroll().resetUpScroll();
		})
		.catch(() => {
			mescroll.endErr(); // 请求失败, 结束加载
		});
};

const goUrl = (url) => {
	uni.navigateTo({
		url: url
	});
};

const showMore = (item) => {
	showMoreFunc.value = true;
	reportedId.value = item.id;
	isSelf.value = item.isSelf;
	// uni.hideTabBar();
};

const closeMore = () => {
	// uni.showTabBar();
	showMoreFunc.value = false;
};

/**
 * 点击举报
 */
const report = () => {
	closeMore();
	uni.navigateTo({
		url: '/subPages/chaoshan/report?reportType=1&&reportedId=' + reportedId.value
	});
};

/**
 * 分享到微信
 */
const shareWx = () => {
	// #ifdef H5
	uni.showToast({
		title: '当前是网页，无法分享到微信',
		icon: 'error'
	});
	// #endif

	// #ifdef APP
	uni.share({
		provider: 'weixin',
		scene: 'WXSceneSession',
		type: 0,
		href: 'http://uniapp.dcloud.io/',
		title: 'uni-app分享',
		summary: '我正在使用HBuilderX开发uni-app，赶紧跟我一起来体验！',
		imageUrl: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/uni@2x.png',
		success: function (res) {
			console.log('success:' + JSON.stringify(res));
		},
		fail: function (err) {
			console.log('fail:' + JSON.stringify(err));
		}
	});
	// #endif

	// emit('update:show', false);
};
</script>

<style lang="scss">
@import './index.scss';
</style>
